package com.ruoyi.project.WebMoudle.wxOrder.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

import com.ruoyi.common.constant.WxConstant;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PushMsg;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.aspectj.lang.annotation.DataScope;
import com.ruoyi.project.WebMoudle.ShopSuser.domain.ShopSuser;
import com.ruoyi.project.WebMoudle.ShopSuser.service.IShopSuserService;
import com.ruoyi.project.WebMoudle.WxShop.domain.WxShop;
import com.ruoyi.project.WebMoudle.WxShop.service.IWxShopService;
import com.ruoyi.project.WebMoudle.WxUser.domain.WxUser;
import com.ruoyi.project.WebMoudle.WxUser.service.IWxUserService;
import com.ruoyi.project.WebMoudle.accountDetails.domain.AccountDetails;
import com.ruoyi.project.WebMoudle.accountDetails.service.IAccountDetailsService;
import com.ruoyi.project.WebMoudle.streamShop.domain.StreamShop;
import com.ruoyi.project.WebMoudle.streamShop.service.IStreamShopService;
import com.ruoyi.project.WebMoudle.streamTerrace.domain.StreamTerrace;
import com.ruoyi.project.WebMoudle.streamTerrace.service.IStreamTerraceService;
import com.ruoyi.project.WebMoudle.terraceDetail.domain.TerraceDetail;
import com.ruoyi.project.WebMoudle.terraceDetail.service.ITerraceDetailService;
import com.ruoyi.project.WebMoudle.useTerms.domain.UseTerms;
import com.ruoyi.project.WebMoudle.useTerms.service.IUseTermsService;
import com.ruoyi.project.WebMoudle.vipCoupon.domain.VipCoupon;
import com.ruoyi.project.WebMoudle.vipCoupon.service.IVipCouponService;
import com.ruoyi.project.WebMoudle.wxOrder.domain.MoneySum;
import com.ruoyi.project.WebMoudle.wxOrder.domain.MyOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.WebMoudle.wxOrder.mapper.WxOrderMapper;
import com.ruoyi.project.WebMoudle.wxOrder.domain.WxOrder;
import com.ruoyi.project.WebMoudle.wxOrder.service.IWxOrderService;
import com.ruoyi.common.utils.text.Convert;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * 微信订单Service业务层处理
 *
 * @author ruoyi
 * @date 2020-07-09
 */
@Service
public class WxOrderServiceImpl implements IWxOrderService {
    @Autowired
    private WxOrderMapper wxOrderMapper;
    @Autowired
    private IWxUserService wxUserService;
    @Autowired
    private IUseTermsService useTermsService;

    @Autowired
    private IAccountDetailsService accountDetailsService;
    @Autowired
    private IWxShopService wxShopService;
    @Autowired
    private IStreamShopService streamShopService;
    @Autowired
    private IStreamTerraceService streamTerraceService;
    @Autowired
    private IVipCouponService vipCouponService;
    @Autowired
    private IShopSuserService shopSuserService;
    @Autowired
    private ITerraceDetailService terraceDetailService;

    /**
     * 查询微信订单
     *
     * @param id 微信订单ID
     * @return 微信订单
     */
    @Override
    public WxOrder selectWxOrderById(Long id) {
        return wxOrderMapper.selectWxOrderById(id);
    }

    /**
     * 查询微信订单列表
     *
     * @param wxOrder 微信订单
     * @return 微信订单
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<WxOrder> selectWxOrderList(WxOrder wxOrder) {
        return wxOrderMapper.selectWxOrderList(wxOrder);
    }

    /**
     * 新增微信订单
     *
     * @param wxOrder 微信订单
     * @return 结果
     */
    @Override
    public int insertWxOrder(WxOrder wxOrder) {
        wxOrder.setCreateTime(DateUtils.getNowDate());
        return wxOrderMapper.insertWxOrder(wxOrder);
    }

    /**
     * 修改微信订单
     *
     * @param wxOrder 微信订单
     * @return 结果
     */
    @Override
    public int updateWxOrder(WxOrder wxOrder) {
        return wxOrderMapper.updateWxOrder(wxOrder);
    }

    /**
     * 删除微信订单对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteWxOrderByIds(String ids) {
        return wxOrderMapper.deleteWxOrderByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除微信订单信息
     *
     * @param id 微信订单ID
     * @return 结果
     */
    @Override
    public int deleteWxOrderById(Long id) {
        return wxOrderMapper.deleteWxOrderById(id);
    }

    @Override
    public WxOrder selectWxOrderByOrderNum(String orderNum) {
        return wxOrderMapper.selectWxOrderByOrderNum(orderNum);
    }


    /**
     * 支付完成后  更新订单和插入账目数据
     *
     * @param wxOrder
     * @return
     */
    @Override
    @Transactional
    public Boolean successPay(WxOrder wxOrder) {
        try {
            WxUser user = wxUserService.selectWxUserById(wxOrder.getWxUserId());
            if (StringUtils.isNotNull(wxOrder.getUseJifen())) {   //使用了积分
                user.setJiFen(user.getJiFen() - wxOrder.getUseJifen());   //扣除积分
            }
            if (StringUtils.isNotNull(wxOrder.getCouponId())) {    //使用了优惠券进行标记
                VipCoupon vipCoupon = vipCouponService.selectMyCoupon(wxOrder.getCouponId(), wxOrder.getWxUserId());
                vipCoupon.setStatus("1");   //设置为已使用状态
                vipCouponService.updateVipCoupon(vipCoupon);
            }

            UseTerms terms = useTermsService.selectUseTermsList(null).get(0);
            AccountDetails accountDetails = new AccountDetails();
            accountDetails.setOrderId(wxOrder.getId());
            //1.存在归属商家则返利到其商家账户   ==用户实际支付价格*让利比*返利比
            BigDecimal terraceRatio = new BigDecimal("1");
            if (StringUtils.isNotNull(user.getShopId())) {
                BigDecimal belongShop$ = wxOrder.getRealityPrice().multiply(wxOrder.getShopDiscount()).multiply(terms.getBelongRatio()).setScale(2, BigDecimal.ROUND_DOWN);   //归属商家返利
                wxShopService.updateMoney(user.getShopId(), belongShop$);  //修改归属商家金额
                accountDetails.setBelongMoney(belongShop$);
                terraceRatio = terraceRatio.subtract(terms.getBelongRatio());
                //插入商家流水表
                StreamShop streamShop = new StreamShop();
                streamShop.setShopId(wxOrder.getShopId());
                streamShop.setBelongId(user.getShopId());
                streamShop.setWxUserId(wxOrder.getWxUserId());
                streamShop.setStreamMoney(belongShop$);
                streamShop.setStreamType("会员支付返利");
                streamShop.setHandleType("2");
                streamShop.setOrderNum(wxOrder.getOrderNum());
                streamShopService.insertStreamShop(streamShop);
            }
            //2.返还用户积分 ==用户实际支付价格*让利比*积分返还比*10
            if (StringUtils.isNotEmpty(user.getPhoneNum())) {     //绑定了手机号
                int userJf = wxOrder.getRealityPrice().multiply(wxOrder.getShopDiscount()).multiply(terms.getReturnRatio()).multiply(new BigDecimal("10")).intValue();
                user.setJiFen(user.getJiFen() + userJf);    //增加积分
                accountDetails.setReturnJifen(userJf);     //返还积分数
                terraceRatio = terraceRatio.subtract(terms.getReturnRatio());
            }

            int j = wxUserService.updateWxUser(user);//修改用户积分
            BigDecimal $terrace = wxOrder.getRealityPrice().multiply(wxOrder.getShopDiscount()).multiply(terraceRatio).setScale(2, BigDecimal.ROUND_DOWN).subtract(wxOrder.getReduceMoney());
            accountDetails.setTerraceMoney($terrace);  //平台得到的钱-优惠券

            //3.在店消费商家得钱
            //用户本身价格的钱*1-让利比
            BigDecimal nowShop$ = wxOrder.getBeforePrice().multiply(new BigDecimal("1").subtract(wxOrder.getShopDiscount())).setScale(2, BigDecimal.ROUND_DOWN);
            WxShop wxShop = wxShopService.selectWxShopById(wxOrder.getShopId());  //查询该商铺
            int m = wxShopService.updateMoney(wxOrder.getShopId(), nowShop$);  //修改当前店铺的金额
            accountDetails.setShopMoney(nowShop$);
            int k = accountDetailsService.insertAccountDetails(accountDetails);   //插入账目详情表
            wxOrder.setStatus(WxConstant.OD_PAY_YES);         //已支付
            int i = wxOrderMapper.updateWxOrder(wxOrder);    //修改为支付完成状态订单

            //公众号推送消息通知商家
            List<String> openIds = shopSuserService.queryShopWxEmp(wxOrder.getShopId());
            PushMsg.pushWxUser(openIds,wxOrder.getBeforePrice(),wxShop.getShopName(),wxOrder.getOrderNum(),wxOrder.getShopId());

            /*插入流水表*/
            //1.插入商家流水表
            StreamShop streamShop = new StreamShop();
            streamShop.setShopId(wxOrder.getShopId());
            streamShop.setWxUserId(wxOrder.getWxUserId());
            streamShop.setStreamMoney(nowShop$);
            streamShop.setStreamType("用户支付"+wxOrder.getBeforePrice()+"元");
            streamShop.setHandleType("0");
            streamShop.setOrderNum(wxOrder.getOrderNum());
            streamShopService.insertStreamShop(streamShop);
            //2.插入平台收入表
            StreamTerrace streamTerrace = new StreamTerrace();
            streamTerrace.setGainType("用户支付"+wxOrder.getBeforePrice()+"元");
            streamTerrace.setGainMoney(wxOrder.getRealityPrice());
            streamTerrace.setOrderNum(wxOrder.getOrderNum());
            streamTerrace.setHandleType("0");
            streamTerraceService.insertStreamTerrace(streamTerrace);
            //3.收益插入平台账单
            TerraceDetail terraceDetail = new TerraceDetail();
            terraceDetail.setHandleName(user.getNickName());
            terraceDetail.setOperateMoney($terrace);
            terraceDetail.setOperateType("5");
            terraceDetailService.insertTerraceDetail(terraceDetail);
            //修改平台的钱
            useTermsService.updateTerraceMoney(wxOrder.getRealityPrice());
            if (i > 0 && j > 0 && m > 0 && k > 0) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {

        }
        return false;
    }

    @Override
    public List<MyOrder> queryShopOrderList(Long shopId) {
        return wxOrderMapper.queryShopOrderList(shopId);
    }

    @Override
    public MyOrder queryOrderDetail(Long orderId) {
        return wxOrderMapper.queryOrderDetail(orderId);
    }

    @Override
    public int queryShopOrderCount(Long shopId) {
        return wxOrderMapper.queryShopOrderCount(shopId);
    }

    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public MoneySum queryMoneySum(WxOrder wxOrder) {
        return wxOrderMapper.queryMoneySum(wxOrder);
    }

    @Override
    public List<WxOrder> queryMyOrderList(WxOrder wxOrder) {
        return wxOrderMapper.queryMyOrderList(wxOrder);
    }
}
